#!/bin/sh /etc/rc.common
# Copyright 2023 MOSSDeF, Stan Grishin (stangri@melmac.ca)
# shellcheck disable=SC3043

# shellcheck disable=SC2034
START=94
# shellcheck disable=SC2034
USE_PROCD=1
LC_ALL=C

[ -n "${IPKG_INSTROOT}" ] && return 0

if type extra_command 1>/dev/null 2>&1; then
	extra_command 'allow' 'Allows domain in current block-list and config'
	extra_command 'check' 'Checks if specified domain is found in current block-list'
	extra_command 'check_lists' 'Checks if specified domain is found in enabled block-lists'
	extra_command 'dl' 'Force-downloads all enabled block-list'
	extra_command 'killcache' 'Delete all cached files'
	extra_command 'pause' 'Pauses AdBlocking for specified number of seconds (default: 60)'
	extra_command 'show_blocklist' 'List currently blocked domains'
	extra_command 'sizes' 'Displays the file-sizes of enabled block-lists'
	extra_command 'version' 'Show version information'
fi

readonly packageName='adblock-fast'
readonly PKG_VERSION='dev-test'
readonly packageCompat='2'
readonly serviceName="$packageName $PKG_VERSION"
readonly packageConfigFile="/etc/config/${packageName}"
readonly dnsmasqAddnhostsFile="/var/run/${packageName}/dnsmasq.addnhosts"
readonly dnsmasqAddnhostsCache="/var/run/${packageName}/dnsmasq.addnhosts.cache"
readonly dnsmasqAddnhostsGzip="${packageName}.dnsmasq.addnhosts.gz"
readonly dnsmasqAddnhostsFilter='s|^|127.0.0.1 |;s|$||'
readonly dnsmasqAddnhostsFilterIPv6='s|^|:: |;s|$||'
readonly dnsmasqAddnhostsOutputFilter='s|^127.0.0.1 ||;s|^:: ||;'
readonly dnsmasqConfFile="/tmp/dnsmasq.d/${packageName}"
readonly dnsmasqConfCache="/var/run/${packageName}/dnsmasq.conf.cache"
readonly dnsmasqConfGzip="${packageName}.dnsmasq.conf.gz"
readonly dnsmasqConfFilter='s|^|local=/|;s|$|/|'
readonly dnsmasqConfOutputFilter='s|local=/||;s|/$||;'
readonly dnsmasqIpsetFile="/tmp/dnsmasq.d/${packageName}.ipset"
readonly dnsmasqIpsetCache="/var/run/${packageName}/dnsmasq.ipset.cache"
readonly dnsmasqIpsetGzip="${packageName}.dnsmasq.ipset.gz"
readonly dnsmasqIpsetFilter='s|^|ipset=/|;s|$|/adb|'
readonly dnsmasqIpsetOutputFilter='s|ipset=/||;s|/adb$||;'
readonly dnsmasqNftsetFile="/tmp/dnsmasq.d/${packageName}.nftset"
readonly dnsmasqNftsetCache="/var/run/${packageName}/dnsmasq.nftset.cache"
readonly dnsmasqNftsetGzip="${packageName}.dnsmasq.nftset.gz"
readonly dnsmasqNftsetFilter='s|^|nftset=/|;s|$|/4#inet#fw4#adb4|'
readonly dnsmasqNftsetFilterIPv6='s|^|nftset=/|;s|$|/4#inet#fw4#adb4,6#inet#fw4#adb6|'
readonly dnsmasqNftsetOutputFilter='s|nftset=/||;s|/4#inet#adb#adb4||;'
readonly dnsmasqServersFile="/var/run/${packageName}/dnsmasq.servers"
readonly dnsmasqServersCache="/var/run/${packageName}/dnsmasq.servers.cache"
readonly dnsmasqServersGzip="${packageName}.dnsmasq.servers.gz"
readonly dnsmasqServersFilter='s|^|server=/|;s|$|/|'
readonly dnsmasqServersAllowFilter='s|(.*)|server=/\1/#|'
readonly dnsmasqServersBlockedCountFilter='\|/#|d'
readonly dnsmasqServersOutputFilter='s|server=/||;s|/$||;'
readonly smartdnsDomainSetFile="/var/run/${packageName}/smartdns.domainset"
readonly smartdnsDomainSetCache="/var/run/${packageName}/smartdns.domainset.cache"
readonly smartdnsDomainSetConfig="/var/run/${packageName}/smartdns.domainset.conf"
readonly smartdnsDomainSetGzip="${packageName}.smartdns.domainset.gz"
readonly smartdnsDomainSetFilter=''
readonly smartdnsDomainSetOutputFilter=''
readonly smartdnsIpsetFile="/var/run/${packageName}/smartdns.ipset"
readonly smartdnsIpsetCache="/var/run/${packageName}/smartdns.ipset.cache"
readonly smartdnsIpsetConfig="/var/run/${packageName}/smartdns.ipset.conf"
readonly smartdnsIpsetGzip="${packageName}.smartdns.ipset.gz"
readonly smartdnsIpsetFilter=''
readonly smartdnsIpsetOutputFilter=''
readonly smartdnsNftsetFile="/var/run/${packageName}/smartdns.nftset"
readonly smartdnsNftsetCache="/var/run/${packageName}/smartdns.nftset.cache"
readonly smartdnsNftsetConfig="/var/run/${packageName}/smartdns.nftset.conf"
readonly smartdnsNftsetGzip="${packageName}.smartdns.nftset.gz"
readonly smartdnsNftsetFilter=''
readonly smartdnsNftsetOutputFilter=''
readonly unboundFile="/var/lib/unbound/adb_list.${packageName}"
readonly unboundCache="/var/run/${packageName}/unbound.cache"
readonly unboundGzip="${packageName}.unbound.gz"
readonly unboundFilter='s|^|local-zone: "|;s|$|." always_nxdomain|'
readonly unboundOutputFilter='s|^local-zone: "||;s|." always_nxdomain$||;'
readonly A_TMP="/var/${packageName}.a.tmp"
readonly B_TMP="/var/${packageName}.b.tmp"
readonly SED_TMP="/var/${packageName}.sed.tmp"
readonly uciConfigFile="/etc/config/${packageName}"
readonly runningConfigFile="/dev/shm/${packageName}.config"
readonly runningErrorFile="/dev/shm/${packageName}.error"
readonly runningStatusFile="/dev/shm/${packageName}.status"
readonly hostsFilter='/localhost/d;/^#/d;/^[^0-9]/d;s/^0\.0\.0\.0.//;s/^127\.0\.0\.1.//;s/[[:space:]]*#.*$//;s/[[:cntrl:]]$//;s/[[:space:]]//g;/[`~!@#\$%\^&\*()=+;:"'\'',<>?/\|[{}]/d;/]/d;/\./!d;/^$/d;/[^[:alnum:]_.-]/d;'
readonly domainsFilter='/^#/d;s/[[:space:]]*#.*$//;s/[[:space:]]*$//;s/[[:cntrl:]]$//;/[[:space:]]/d;/[`~!@#\$%\^&\*()=+;:"'\'',<>?/\|[{}]/d;/]/d;/^$/d;/[^[:alnum:]_.-]/d;'
readonly adBlockPlusFilter='/^#/d;/^!/d;s/[[:space:]]*#.*$//;s/^||//;s/\^$//;s/[[:space:]]*$//;s/[[:cntrl:]]$//;/[[:space:]]/d;/[`~!@#\$%\^&\*()=+;:"'\'',<>?/\|[{}]/d;/]/d;/\./!d;/^$/d;/[^[:alnum:]_.-]/d;'
readonly dnsmasqFileFilter='\|^server=/[[:alnum:]_.-].*/|!d;s|server=/||;s|/.*$||'
readonly dnsmasq2FileFilter='\|^local=/[[:alnum:]_.-].*/|!d;s|local=/||;s|/.*$||'
readonly dnsmasq3FileFilter='\|^address=/[[:alnum:]_.-].*/|!d;s|address=/||;s|/.*$||'
readonly _ERROR_='\033[0;31mERROR\033[0m'
readonly _OK_='\033[0;32m\xe2\x9c\x93\033[0m'
readonly _FAIL_='\033[0;31m\xe2\x9c\x97\033[0m'
readonly __OK__='\033[0;32m[\xe2\x9c\x93]\033[0m'
readonly __FAIL__='\033[0;31m[\xe2\x9c\x97]\033[0m'
readonly _WARNING_='\033[0;33mWARNING\033[0m'
# shellcheck disable=SC2155
readonly ipset="$(command -v ipset)"
# shellcheck disable=SC2155
readonly nft="$(command -v nft)"
readonly canaryDomainsMozilla='use-application-dns.net'
readonly canaryDomainsiCloud='mask.icloud.com mask-h2.icloud.com'
readonly triggersReload='parallel_downloads debug download_timeout allowed_domain blocked_domain allowed_url blocked_url dns config_update_enabled config_update_url dnsmasq_config_file_url curl_additional_param curl_max_file_size curl_retry'
readonly triggersRestart='compressed_cache compressed_cache_dir force_dns led force_dns_port'

dl_command=
dl_flag=
isSSLSupported=
outputAllowFilter=
outputBlockedCountFilter=
outputFilter=
outputFilterIPv6=
outputFile=
outputGzip=
outputCache=
outputOutputFilter=
awk='awk'
load_environment_flag=
allowed_url=
blocked_url=
fw4_restart_flag=

# shellcheck disable=SC1091
. /lib/functions.sh
# shellcheck disable=SC1091
. /lib/functions/network.sh
# shellcheck disable=SC1091
. /usr/share/libubox/jshn.sh

append_newline() { is_newline_ending "$1" || echo '' >> "$1"; }
check_ipset() { { command -v ipset && /usr/sbin/ipset help hash:net; } >/dev/null 2>&1; }
check_nft() { command -v nft >/dev/null 2>&1; }
check_dnsmasq() { command -v dnsmasq >/dev/null 2>&1; }
check_dnsmasq_ipset() {
	local o;
	check_dnsmasq || return 1
	o="$(dnsmasq -v 2>/dev/null)"
	check_ipset && ! echo "$o" | grep -q 'no-ipset' && echo "$o" | grep -q 'ipset'
}
check_dnsmasq_nftset() {
	local o;
	check_dnsmasq || return 1
	o="$(dnsmasq -v 2>/dev/null)"
	check_nft && ! echo "$o" | grep -q 'no-nftset' && echo "$o" | grep -q 'nftset'
}
check_smartdns() { command -v smartdns >/dev/null 2>&1; }
check_smartdns_ipset() { check_smartdns && check_ipset; }
check_smartdns_nftset() { check_smartdns && check_nft; }
check_unbound() { command -v unbound >/dev/null 2>&1; }
config_cache() {
	local param="$1" var="$2"
	local _reload="$triggersReload"
	local _restart="$triggersRestart"
	local i ret
	case "$param" in
		create|set)
			cp -f "$uciConfigFile" "$runningConfigFile"
		;;
		get)
			case "$var" in
			trigger_fw4)
				ret='false'
				if [ -s "$runningConfigFile" ]; then
					local UCI_CONFIG_DIR="${runningConfigFile%/*}"
					is_fw4_restart_needed && ret='true'
				fi
				printf "%b" "$ret"
				return
			;;
			trigger_service)
				local old_allowed_url old_blocked_url
				if [ ! -s "$runningConfigFile" ]; then
					ret='on_boot'
				elif cmp -s "$uciConfigFile" "$runningConfigFile"; then
					ret='restart'
				else
					for i in $_reload; do
						local val_current val_old UCI_CONFIG_DIR
						case "$i" in
							allowed_url)
								val_current="$allowed_url"
								config_load "$runningConfigFile"
								config_foreach append_url 'file_url' old_allowed_url old_blocked_url
								val_old="$old_allowed_url"
							;;
							blocked_url)
								val_current="$blocked_url"
								config_load "$runningConfigFile"
								config_foreach append_url 'file_url' old_allowed_url old_blocked_url
								val_old="$old_blocked_url"
							;;
							*)
								UCI_CONFIG_DIR=
								val_current="$(uci_get "$packageName" 'config' "$i")"
								UCI_CONFIG_DIR="${runningConfigFile%/*}"
								val_old="$(uci_get "$packageName" 'config' "$i")"
							;;
						esac
						if [ "$val_current" != "$val_old" ]; then
							ret='download'
							unset _restart
							break
						fi
					done
					for i in $_restart; do
						local val_current val_old UCI_CONFIG_DIR
						UCI_CONFIG_DIR=
						val_current="$(uci_get "$packageName" 'config' "$i")"
						UCI_CONFIG_DIR="${runningConfigFile%/*}"
						val_old="$(uci_get "$packageName" 'config' "$i")"
						if [ "$val_current" != "$val_old" ]; then
							ret='restart'
							break
						fi
					done
				fi
				printf "%b" "$ret"
				return
			;;
			*)
				local UCI_CONFIG_DIR="${runningConfigFile%/*}"
				ret="$(uci_get "$packageName" 'config' "$var")"
				printf "%b" "$ret"
				return
			;;
		esac
	;;
	esac
}
count_blocked_domains() {
	if [ -n "$outputBlockedCountFilter" ]; then
		sed "$outputBlockedCountFilter" "$outputFile" | wc -l
	else
		wc -l < "$outputFile"
	fi
}
debug() { local __i __j; for __i in "$@"; do eval "__j=\$$__i"; echo "${__i}: ${__j} "; done; }
dns_set_output_values() {
	case "$1" in
		dnsmasq.addnhosts)
			outputFilter="$dnsmasqAddnhostsFilter"
			outputFile="$dnsmasqAddnhostsFile"
			outputCache="$dnsmasqAddnhostsCache"
			outputGzip="${compressed_cache_dir}/${dnsmasqAddnhostsGzip}"
			outputOutputFilter="$dnsmasqAddnhostsOutputFilter"
			if [ "$ipv6_enabled" -ne '0' ]; then
				outputFilterIPv6="$dnsmasqAddnhostsFilterIPv6"
			fi
		;;
		dnsmasq.conf)
			outputFilter="$dnsmasqConfFilter"
			outputFile="$dnsmasqConfFile"
			outputCache="$dnsmasqConfCache"
			outputGzip="${compressed_cache_dir}/${dnsmasqConfGzip}"
			outputOutputFilter="$dnsmasqConfOutputFilter"
		;;
		dnsmasq.ipset)
			outputFilter="$dnsmasqIpsetFilter"
			outputFile="$dnsmasqIpsetFile"
			outputCache="$dnsmasqIpsetCache"
			outputGzip="${compressed_cache_dir}/${dnsmasqIpsetGzip}"
			outputOutputFilter="$dnsmasqIpsetOutputFilter"
		;;
		dnsmasq.nftset)
			if [ "$ipv6_enabled" -ne '0' ]; then
				outputFilter="$dnsmasqNftsetFilterIPv6"
			else
				outputFilter="$dnsmasqNftsetFilter"
			fi
			outputFile="$dnsmasqNftsetFile"
			outputCache="$dnsmasqNftsetCache"
			outputGzip="${compressed_cache_dir}/${dnsmasqNftsetGzip}"
			outputOutputFilter="$dnsmasqNftsetOutputFilter"
		;;
		dnsmasq.servers)
			outputFilter="$dnsmasqServersFilter"
			outputFile="$dnsmasqServersFile"
			outputCache="$dnsmasqServersCache"
			outputGzip="${compressed_cache_dir}/${dnsmasqServersGzip}"
			outputOutputFilter="$dnsmasqServersOutputFilter"
			outputAllowFilter="$dnsmasqServersAllowFilter"
			outputBlockedCountFilter="$dnsmasqServersBlockedCountFilter"
		;;
		smartdns.domainset)
			outputFilter="$smartdnsDomainSetFilter"
			outputFile="$smartdnsDomainSetFile"
			outputCache="$smartdnsDomainSetCache"
			outputGzip="${compressed_cache_dir}/${smartdnsDomainSetGzip}"
			outputConfig="$smartdnsDomainSetConfig"
			outputOutputFilter="$smartdnsDomainSetOutputFilter"
		;;
		smartdns.ipset)
			outputFilter="$smartdnsIpsetFilter"
			outputFile="$smartdnsIpsetFile"
			outputCache="$smartdnsIpsetCache"
			outputGzip="${compressed_cache_dir}/${smartdnsIpsetGzip}"
			outputConfig="$smartdnsIpsetConfig"
			outputOutputFilter="$smartdnsIpsetOutputFilter"
		;;
		smartdns.nftset)
			outputFilter="$smartdnsNftsetFilter"
			outputFile="$smartdnsNftsetFile"
			outputCache="$smartdnsNftsetCache"
			outputGzip="${compressed_cache_dir}/${smartdnsNftsetGzip}"
			outputConfig="$smartdnsNftsetConfig"
			outputOutputFilter="$smartdnsNftsetOutputFilter"
		;;
		unbound.adb_list)
			outputFilter="$unboundFilter"
			outputFile="$unboundFile"
			outputCache="$unboundCache"
			outputGzip="${compressed_cache_dir}/${unboundGzip}"
			outputOutputFilter="$unboundOutputFilter"
		;;
	esac
}
dnsmasq_hup() { killall -q -s HUP dnsmasq; }
dnsmasq_kill() { killall -q -s KILL dnsmasq; }
dnsmasq_restart() { /etc/init.d/dnsmasq restart >/dev/null 2>&1; }
is_enabled() { uci_get "$1" 'config' 'enabled' '0'; }
is_fw4_restart_needed() {
	[ "$fw4_restart_flag" = 'true' ] && return 0
	local dns force_dns
	dns="$(uci_get "$packageName" 'config' 'dns' 'dnsmasq.servers')"
	force_dns="$(uci_get "$packageName" 'config' 'force_dns' '1')"
	if [ "$force_dns" = '1' ]; then
		return 0
	elif [ "$dns" = 'dnsmasq.ipset' ]; then
		return 0
	elif [ "$dns" = 'dnsmasq.nftset' ]; then
		return 0
	elif [ "$dns" = 'smartdns.ipset' ]; then
		return 0
	elif [ "$dns" = 'smartdns.nftset' ]; then
		return 0
	else
		return 1
	fi
}
is_integer() { case "$1" in ''|*[!0-9]*) return 1;; esac; }
is_greater() { test "$(printf '%s\n' "$@" | sort -V | head -n 1)" != "$1"; }
is_greater_or_equal() { test "$(printf '%s\n' "$@" | sort -V | head -n 1)" = "$2"; }
# shellcheck disable=SC3057
is_https_url() { [ "${1:0:8}" = "https://" ]; }
is_newline_ending() { [ "$(tail -c1 "$1" | wc -l)" -ne '0' ]; }
is_present() { command -v "$1" >/dev/null 2>&1; }
is_running() {
	local i j
	i="$(json 'get' 'status')"
	j="$(ubus_get_data 'status')"
	if [ "$i" = 'statusStopped' ] || [ -z "${i}${j}" ]; then
		return 1
	else
		return 0
	fi
}
ipset() { "$ipset" "$@" >/dev/null 2>&1; }
get_ram_available() { ubus call system info | jsonfilter -e '@.memory.available'; }
get_ram_free() { ubus call system info | jsonfilter -e '@.memory.free'; }
get_ram_total() { ubus call system info | jsonfilter -e '@.memory.total'; }
led_on(){ if [ -n "${1}" ] && [ -e "${1}/trigger" ]; then echo 'default-on' > "${1}/trigger" 2>&1; fi; }
led_off(){ if [ -n "${1}" ] &&  [ -e "${1}/trigger" ]; then echo 'none' > "${1}/trigger" 2>&1; fi; }
logger() { /usr/bin/logger -t "$packageName" "$@"; }
nft() { "$nft" "$@" >/dev/null 2>&1; }
output_ok() { output 1 "$_OK_"; output 2 "$__OK__\n"; }
output_okn() { output 1 "$_OK_\n"; output 2 "$__OK__\n"; }
output_fail() { output 1 "$_FAIL_"; output 2 "$__FAIL__\n"; }
output_failn() { output 1 "$_FAIL_\n"; output 2 "$__FAIL__\n"; }
print_json_bool() { json_init; json_add_boolean "$1" "$2"; json_dump; json_cleanup; }
print_json_int() { json_init; json_add_int "$1" "$2"; json_dump; json_cleanup; }
print_json_string() { json_init; json_add_string "$1" "$2"; json_dump; json_cleanup; }
sanitize_dir() { [ -d "$(readlink -fn "$1")" ] && readlink -fn "$1"; }
smartdns_restart() { /etc/init.d/smartdns restart >/dev/null 2>&1; }
str_contains() { test "$1" != "$(str_replace "$1" "$2" '')"; }
str_contains_word() { echo "$1" | grep -q -w "$2"; }
# shellcheck disable=SC2018,SC2019
str_to_lower() { echo "$1" | tr 'A-Z' 'a-z'; }
# shellcheck disable=SC2018,SC2019
str_to_upper() { echo "$1" | tr 'a-z' 'A-Z'; }
str_replace() { printf "%b" "$1" | sed -e "s/$(printf "%b" "$2")/$(printf "%b" "$3")/g"; }
ubus_get_data() { ubus call service list "{ 'name': '$packageName' }" | jsonfilter -e "@['${packageName}'].instances.main.data.${1}"; }
ubus_get_ports() { ubus call service list "{ 'name': '$packageName' }" | jsonfilter -e "@['${packageName}'].instances.main.data.firewall.*.dest_port"; }
uci_get_protocol() { uci_get 'network' "$1" 'proto'; }
unbound_restart() { /etc/init.d/unbound restart >/dev/null 2>&1; }

json() {
# shellcheck disable=SC2034
	local action="$1" param="$2" value="$3"
	shift 3
# shellcheck disable=SC2124
	local extras="$@" line
	local status message error stats
	local ret i
	if [ -s "$runningStatusFile" ]; then
		json_load_file "$runningStatusFile" 2>/dev/null
		json_select 'data' 2>/dev/null
		for i in status message error stats; do
			json_get_var "$i" "$i" 2>/dev/null
		done
	fi
	case "$action" in
		get)
			printf "%b" "$(eval echo "\$$param")"
			return
		;;
		add)
			line="$(eval echo "\$$param")"
			eval "$param"='${line:+$line }${value}${extras:+|$extras}'
		;;
		del)
			case "$param" in
				all)
					unset status message error stats;;
				*)
					unset "$param";;
			esac
		;;
		set)
			eval "$param"='${value}${extras:+|$extras}'
		;;
	esac
	json_init
	json_add_object 'data'
	json_add_string version "$PKG_VERSION"
	json_add_string status "$status"
	json_add_string message "$message"
	json_add_string error "$error"
	json_add_string stats "$stats"
	json_close_object
	mkdir -p "${runningStatusFile%/*}"
	json_dump > "$runningStatusFile"
	sync
}

get_local_filesize() {
	local file="$1" size
	[ -f "$file" ] || return 0
	if is_present stat; then
		size="$(stat -c%s "$file")"
	elif is_present wc; then
		size="$(wc -c < "$file")"
	fi
# shellcheck disable=SC3037
	echo -en "$size"
}

get_url_filesize() {
	local url="$1" size size_command
	[ -n "$url" ] || return 0
	is_present 'curl' || return 0
	size_command='curl --silent --insecure --fail --head --request GET'
#	size="$($size_command "$url" | grep -Po '^[cC]ontent-[lL]ength: \K\w+')"
	size="$($size_command "$url" | grep -Eo '^[cC]ontent-[lL]ength: (.*)' | awk '{print $2}')"
# shellcheck disable=SC3037
	echo -en "$size"
}

output() {
# Target verbosity level with the first parameter being an integer
	is_integer() { case "$1" in ''|*[!0-9]*) return 1;; esac; }
	local msg memmsg logmsg text
	local sharedMemoryOutput="/dev/shm/$packageName-output"
	if [ -z "$verbosity" ] && [ -n "$packageName" ]; then
		verbosity="$(uci_get "$packageName" 'config' 'verbosity' '2')"
	fi
	if [ $# -ne 1 ] && is_integer "$1"; then
		if [ $((verbosity & $1)) -gt 0 ] || [ "$verbosity" = "$1" ]; then shift; text="$*"; else return 0; fi
	fi
	text="${text:-$*}";
	[ -t 1 ] && printf "%b" "$text"
# shellcheck disable=SC3060
	msg="${text//$serviceName /service }";
	if [ "$(printf "%b" "$msg" | wc -l)" -gt 0 ]; then
		[ -s "$sharedMemoryOutput" ] && memmsg="$(cat "$sharedMemoryOutput")"
		logmsg="$(printf "%b" "${memmsg}${msg}" | sed 's/\x1b\[[0-9;]*m//g')"
		logger -t "${packageName:-service} [$$]" "$(printf "%b" "$logmsg")"
		rm -f "$sharedMemoryOutput"
	else
		printf "%b" "$msg" >> "$sharedMemoryOutput"
	fi
}

uci_add_list_if_new() {
	local PACKAGE="$1"
	local CONFIG="$2"
	local OPTION="$3"
	local VALUE="$4"
	local i
	[ -n "$PACKAGE" ] && [ -n "$CONFIG" ] && [ -n "$OPTION" ] && [ -n "$VALUE" ] || return 1
	for i in $(uci_get "$PACKAGE" "$CONFIG" "$OPTION"); do
		[ "$i" = "$VALUE" ] && return 0
	done
	uci_add_list "$PACKAGE" "$CONFIG" "$OPTION" "$VALUE"
}

uci_changes() {
	local PACKAGE="$1"
	local CONFIG="$2"
	local OPTION="$3"
	if [ -s "${UCI_CONFIG_DIR:-/etc/config/}${PACKAGE}" ]; then
		/sbin/uci ${UCI_CONFIG_DIR:+-c $UCI_CONFIG_DIR} changes "$PACKAGE${CONFIG:+.$CONFIG}${OPTION:+.$OPTION}"
	fi
}

get_text() {
	local r
	case "$1" in
		errorConfigValidationFail) r="$packageName config validation failed";;
		errorServiceDisabled) r="$packageName is currently disabled";;
		errorNoDnsmasqIpset) 
			r="dnsmasq ipset support is enabled in $packageName, but dnsmasq is either not installed or installed dnsmasq does not support ipset";;
		errorNoIpset) 
			r="dnsmasq ipset support is enabled in $packageName, but ipset is either not installed or installed ipset does not support 'hash:net' type";;
		errorNoDnsmasqNftset) 
			r="dnsmasq nft set support is enabled in $packageName, but dnsmasq is either not installed or installed dnsmasq does not support nft set";;
		errorNoNft) r="dnsmasq nft sets support is enabled in $packageName, but nft is not installed";;
		errorNoWanGateway) r="The ${serviceName} failed to discover WAN gateway";;
		errorOutputDirCreate) r="failed to create directory for %s file";;
		errorOutputFileCreate) r="failed to create $outputFile file";;
		errorFailDNSReload) r="failed to restart/reload DNS resolver";;
		errorSharedMemory) r="failed to access shared memory";;
		errorSorting) r="failed to sort data file";;
		errorOptimization) r="failed to optimize data file";;
		errorAllowListProcessing) r="failed to process allow-list";;
		errorDataFileFormatting) r="failed to format data file";;
		errorMovingDataFile) r="failed to move data file '${A_TMP}' to '${outputFile}'";;
		errorCreatingCompressedCache) r="failed to create compressed cache";;
		errorRemovingTempFiles) r="failed to remove temporary files";;
		errorRestoreCompressedCache) r="failed to unpack compressed cache";;
		errorRestoreCache) r="failed to move '$outputCache' to '$outputFile'";;
		errorOhSnap) r="failed to create block-list or restart DNS resolver";;
		errorStopping) r="failed to stop $serviceName";;
		errorDNSReload) r="failed to reload/restart DNS resolver";;
		errorDownloadingConfigUpdate) r="failed to download Config Update file";;
		errorDownloadingList) r="failed to download";;
		errorParsingConfigUpdate) r="failed to parse Config Update file";;
		errorParsingList) r="failed to parse";;
		errorNoSSLSupport) r="no HTTPS/SSL support on device";;
		errorCreatingDirectory) r="failed to create output/cache/gzip file directory";;
		errorDetectingFileType) r="failed to detect format";;
		errorNothingToDo) r="no blocked list URLs nor blocked-domains enabled";;
		errorTooLittleRam) r="free ram (%s) is not enough to process all enabled block-lists";;

		statusNoInstall) r="$serviceName is not installed or not found";;
		statusStopped) r="Stopped";;
		statusStarting) r="Starting";;
		statusRestarting) r="Restarting";;
		statusForceReloading) r="Force Reloading";;
		statusDownloading) r="Downloading";;
		statusProcessing) r="Processing";;
		statusFail) r="failed to start";;
		statusSuccess) r="Success";;

		warningExternalDnsmasqConfig)
			r="use of external dnsmasq config file detected, please set 'dns' option to 'dnsmasq.conf'";;
		warningMissingRecommendedPackages) r="some recommended packages are missing";;
		warningInvalidCompressedCacheDir) r="invalid compressed cache directory '%s'";;
		warningFreeRamCheckFail) r="can't detect free RAM";;
	esac
	shift
# shellcheck disable=SC2059
	printf "$r" "$@"
}

load_network() {
	local param="$1"
	local i j wan_if wan_gw
	local counter wan_if_timeout="$procd_boot_wan_timeout" wan_gw_timeout='5'
	counter=0
	while [ -z "$wan_if" ]; do
		network_flush_cache
		network_find_wan wan_if
		if [ -n "$wan_if" ]; then
			output "WAN interface found: '${wan_if}'.\n"
			break
		fi
		if [ "$counter" -gt "$wan_if_timeout" ]; then
			output "WAN interface timeout, assuming 'wan'.\n"
			wan_if='wan'
			break
		fi
		counter=$((counter+1))
		output "Waiting to discover WAN Interface...\n"
		sleep 1
	done

	counter=0
	if [ "$(uci_get_protocol "$wan_if")" = 'pppoe' ]; then
		wan_gw_timeout=$((wan_gw_timeout+10))
	fi
	while [ "$counter" -le "$wan_gw_timeout" ]; do
		network_flush_cache
		network_get_gateway wan_gw "$wan_if"
		if [ -n "$wan_gw" ]; then
			output "WAN gateway found: '${wan_gw}.'\n"
			return 0
		fi
		counter=$((counter+1))
		output "Waiting to discover $wan_if gateway...\n"
		sleep 1
	done
	json add error 'errorNoWanGateway'
	output "${_ERROR_}: $(get_text 'errorNoWanGateway')!\n"; return 1;
}

append_url() {
	local cfg="$1" allow_var="${2:-allowed_url}" block_var="${3:-blocked_url}"
	local old_value
	local en action url
	config_get_bool en "$cfg" enabled '1'
	config_get action "$cfg" action 'block'
	config_get url "$cfg" url
	if [ "$en" = '1' ]; then
		if [ "$action" = 'allow' ]; then
			old_value=$(eval echo "\$$allow_var")
			old_value="${old_value:+$old_value }${url}"
			eval "$allow_var"="\$old_value"
		else
			old_value=$(eval echo "\$$block_var")
			old_value="${old_value:+$old_value }${url}"
			eval "$block_var"="\$old_value"
		fi
	fi
}

detect_file_type() {
	local file="$1"
	if [ "$(head -1 "$file")" = '[Adblock Plus]' ] || \
		grep -q '^||' "$file"; then
		echo 'adblockplus'
	elif grep -q '^server=' "$file"; then
		echo 'dnsmasq'
	elif grep -q '^local=' "$file"; then
		echo 'dnsmasq2'
	elif grep -q '^address=' "$file"; then
		echo 'dnsmasq3'
	elif grep -q '^0\.0\.0\.0' "$file" || grep -q '^127\.0\.0\.1' "$file"; then
		echo 'hosts'
	elif [ -n "$(sed "$domainsFilter" "$file" | head -1)" ]; then
		echo 'domains'
	fi
}

load_environment() {
	local i j
	local validation_result="$1" param="$2"

	[ -z "$load_environment_flag" ] || return 0

	if [ "$validation_result" != '0' ]; then
		json add error 'errorConfigValidationFail'
		output "${_ERROR_}: $(get_text 'errorConfigValidationFail')!\n"
		output "Please check if the '$packageConfigFile' contains correct values for config options.\n"
		return 1
	fi

	if [ "$enabled" -eq 0 ]; then
		json add error 'errorServiceDisabled'
		output "${_ERROR_}: $(get_text 'errorServiceDisabled')!\n"
		output "Run the following commands before starting service again:\n"
		output "uci set ${packageName}.config.enabled='1'; uci commit $packageName;\n"
		return 1
	fi

	if [ "$debug" -ne '0' ]; then
		exec 1>>"/tmp/$packageName.log"
		exec 2>&1
		set -x
	fi

# TODO: check for resolver and error out on start

	if [ -n "$dnsmasq_config_file_url" ]; then
		case "$dns" in
			dnsmasq.conf) :;;
			*)
				if [ "$param" != 'quiet' ]; then
					json add warning 'warningExternalDnsmasqConfig'
					output "${_WARNING_}: $(get_text 'warningExternalDnsmasqConfig')!\n"
				fi
			;;
		esac
	fi

	case "$dns" in
		dnsmasq.*)
			if dnsmasq -v 2>/dev/null | grep -q 'no-IDN' || ! dnsmasq -v 2>/dev/null | grep -q -w 'IDN'; then
				allow_non_ascii='0'
			fi
		;;
		smartdns.*)
			allow_non_ascii='0'
		;;
		unbound.*)
			allow_non_ascii='1'
		;;
	esac

	case "$dns" in
		dnsmasq.ipset)
			if dnsmasq -v 2>/dev/null | grep -q 'no-ipset' || ! dnsmasq -v 2>/dev/null | grep -q -w 'ipset'; then
				if [ "$param" != 'quiet' ]; then
					json add error 'errorNoDnsmasqIpset'
					output "${_ERROR_}: $(get_text 'errorNoDnsmasqIpset')!\n"
				fi
				dns='dnsmasq.servers'
			fi
			if ! ipset help hash:net; then
				if [ "$param" != 'quiet' ]; then
					json add error 'errorNoIpset'
					output "${_ERROR_}: $(get_text 'errorNoIpset')!\n"
				fi
				dns='dnsmasq.servers'
			fi
		;;
		dnsmasq.nftset)
			if dnsmasq -v 2>/dev/null | grep -q 'no-nftset' || ! dnsmasq -v 2>/dev/null | grep -q -w 'nftset'; then
				if [ "$param" != 'quiet' ]; then
					json add error 'errorNoDnsmasqNftset'
					output "${_ERROR_}: $(get_text 'errorNoDnsmasqNftset')!\n"
				fi
				dns='dnsmasq.servers'
			fi
			if [ -z "$nft" ]; then
				if [ "$param" != 'quiet' ]; then
					json add error 'errorNoNft'
					output "${_ERROR_}: $(get_text 'errorNoNft')!\n"
				fi
				dns='dnsmasq.servers'
			fi
		;;
		smartdns.ipset)
			if ! ipset help hash:net; then
				if [ "$param" != 'quiet' ]; then
					json add error 'errorNoIpset'
					output "${_ERROR_}: $(get_text 'errorNoIpset')!\n"
				fi
				dns='smartdns.domainset'
			fi
		;;
		smartdns.nftset)
			if [ -z "$nft" ]; then
				if [ "$param" != 'quiet' ]; then
					json add error 'errorNoNft'
					output "${_ERROR_}: $(get_text 'errorNoNft')!\n"
				fi
				dns='smartdns.domainset'
			fi
		;;
	esac

	if [ "$(sanitize_dir "$compressed_cache_dir")" = '/' ]; then
		compressed_cache_dir=''
	elif [ -n "$(sanitize_dir "$compressed_cache_dir")" ]; then
		compressed_cache_dir="$(sanitize_dir "$compressed_cache_dir")"
	else
		json add warning 'warningInvalidCompressedCacheDir' "$compressed_cache_dir"
		output "${_WARNING_}: $(get_text 'warningInvalidCompressedCacheDir' "$compressed_cache_dir")!\n"
		compressed_cache_dir="/etc"
	fi

	dns_set_output_values "$dns"

	[ "$dns" = 'dnsmasq.addnhosts' ]  || rm -f "$dnsmasqAddnhostsFile" "$dnsmasqAddnhostsCache" "${compressed_cache_dir}/${dnsmasqAddnhostsGzip}"
	[ "$dns" = 'dnsmasq.conf' ]       || rm -f "$dnsmasqConfFile" "$dnsmasqConfCache" "${compressed_cache_dir}/${dnsmasqConfGzip}"
	[ "$dns" = 'dnsmasq.ipset' ]      || rm -f "$dnsmasqIpsetFile" "$dnsmasqIpsetCache" "${compressed_cache_dir}/${dnsmasqIpsetGzip}"
	[ "$dns" = 'dnsmasq.nftset' ]     || rm -f "$dnsmasqNftsetFile" "$dnsmasqNftsetCache" "${compressed_cache_dir}/${dnsmasqNftsetGzip}"
	[ "$dns" = 'dnsmasq.servers' ]    || rm -f "$dnsmasqServersFile" "$dnsmasqServersCache" "${compressed_cache_dir}/${dnsmasqServersGzip}"
	[ "$dns" = 'smartdns.domainset' ] || rm -f "$smartdnsDomainSetFile" "$smartdnsDomainSetCache" "${compressed_cache_dir}/${smartdnsDomainSetGzip}" "$smartdnsDomainSetConfig"
	[ "$dns" = 'smartdns.ipset' ]     || rm -f "$smartdnsIpsetFile" "$smartdnsIpsetCache" "${compressed_cache_dir}/${smartdnsIpsetGzip}" "$smartdnsIpsetConfig"
	[ "$dns" = 'smartdns.nftset' ]    || rm -f "$smartdnsNftsetFile" "$smartdnsNftsetCache" "${compressed_cache_dir}/${smartdnsNftsetGzip}" "$smartdnsNftsetConfig"
	[ "$dns" = 'unbound.adb_list' ]   || rm -f "$unboundFile" "$unboundCache" "${compressed_cache_dir}/${unboundGzip}"

	for i in "$runningConfigFile" "$runningErrorFile" "$runningStatusFile" "$outputFile" "$outputCache" "$outputGzip" "$outputConfig"; do
		[ -n "$i" ] || continue
		if ! mkdir -p "${i%/*}"; then
			if [ "$param" != 'quiet' ]; then
				json add error 'errorOutputDirCreate' "$i"
				output "${_ERROR_}: $(get_text 'errorOutputDirCreate' "$i")!\n"
			fi
		fi
	done

	is_present 'gawk' && awk='gawk'
	if ! is_present '/usr/libexec/grep-gnu' || ! is_present '/usr/libexec/sed-gnu' || \
		! is_present '/usr/libexec/sort-coreutils' || ! is_present 'gawk'; then
			local s
			is_present 'gawk' || s="${s:+$s }gawk"
			is_present '/usr/libexec/grep-gnu' || s="${s:+$s }grep"
			is_present '/usr/libexec/sed-gnu' || s="${s:+$s }sed"
			is_present '/usr/libexec/sort-coreutils' || s="${s:+$s }coreutils-sort"
			if [ "$param" != 'quiet' ]; then
				json add warning 'warningMissingRecommendedPackages' "$s"
				output "${_WARNING_}: $(get_text 'warningMissingRecommendedPackages'), install them by running:\n"
				output "opkg update; opkg --force-overwrite install $s;\n"
			fi
	fi
	# Prefer curl because it supports the file:// scheme.
	if is_present 'curl'; then
		dl_command='curl --silent --insecure'
		dl_command="${dl_command}${curl_additional_param:+ $curl_additional_param}"
		dl_command="${dl_command}${curl_max_file_size:+ --max-filesize $curl_max_file_size}"
		dl_command="${dl_command}${curl_retry:+ --retry $curl_retry}"
		dl_command="${dl_command}${download_timeout:+ --connect-timeout $download_timeout}"
		dl_flag='-o'
	elif is_present '/usr/libexec/wget-ssl'; then
		dl_command='/usr/libexec/wget-ssl --no-check-certificate -q'
		dl_command="${dl_command}${download_timeout:+ --timeout $download_timeout}"
		dl_flag="-O"
		size_command='/usr/libexec/wget-ssl --no-check-certificate -q -O /dev/null --server-response'
		size_command="${size_command}${download_timeout:+ --timeout $download_timeout}"
	elif is_present wget && wget --version 2>/dev/null | grep -q "+https"; then
		dl_command="wget --no-check-certificate -q"
		dl_command="${dl_command}${download_timeout:+ --timeout $download_timeout}"
		dl_flag="-O"
		size_command='wget --no-check-certificate -q -O /dev/null --server-response'
		size_command="${size_command}${download_timeout:+ --timeout $download_timeout}"
	else
		dl_command="uclient-fetch --no-check-certificate -q"
		dl_command="${dl_command}${download_timeout:+ --timeout $download_timeout}"
		dl_flag="-O"
	fi
	led="${led:+/sys/class/leds/$led}"
	if curl --version 2>/dev/null | grep -q "Protocols: .*https.*" \
		|| wget --version 2>/dev/null | grep -q "+ssl"; then
		isSSLSupported=1
	else
		unset isSSLSupported
	fi
	config_load "$packageName"
	config_foreach append_url 'file_url'
	load_environment_flag=1
	cache 'test' && return 0 
	cache 'test_gzip' && return 0
	if [ "$param" = 'on_boot' ]; then
		load_network "$param"
		return "$?"
	else
		return 0
	fi
}

resolver() {
	_dnsmasq_instance_config() {
		local cfg="$1" param="$2"
		[ -s "/etc/config/dhcp" ] || return 0
		case "$param" in
			dnsmasq.addnhosts)
				if [ "$(uci_get 'dhcp' "$cfg" 'serversfile')" = "$dnsmasqServersFile" ]; then
					uci_remove 'dhcp' "$cfg" 'serversfile'
				fi
				uci_add_list_if_new 'dhcp' "$cfg" 'addnhosts' "$dnsmasqAddnhostsFile"
			;;
			cleanup|dnsmasq.conf|dnsmasq.ipset|dnsmasq.nftset|unbound.adb_list)
				uci_remove_list 'dhcp' "$cfg" 'addnhosts' "$dnsmasqAddnhostsFile"
				if [ "$(uci_get 'dhcp' "$cfg" 'serversfile')" = "$dnsmasqServersFile" ]; then
					uci_remove 'dhcp' "$cfg" 'serversfile'
				fi
			;;
			dnsmasq.servers)
				uci_remove_list 'dhcp' "$cfg" 'addnhosts' "$dnsmasqAddnhostsFile"
				if [ "$(uci_get 'dhcp' "$cfg" 'serversfile')" != "$dnsmasqServersFile" ]; then
					uci_set 'dhcp' "$cfg" 'serversfile' "$dnsmasqServersFile"
				fi
			;;
		esac
	}
	_smartdns_instance_config() {
		[ -s "/etc/config/smartdns" ] || return 0
		local cfg="$1" param="$2"
		case "$param" in
			cleanup)
				uci_remove_list 'smartdns' "$cfg" 'conf_files' "$outputConfig"
				rm -f "$outputConfig"
			;;
			smartdns.domainset)
				{ echo "domain-set -name adblock-fast -file $outputFile"; \
				echo "domain-rules /domain-set:adblock-fast/ -a #"; } > "$outputConfig"
				uci_add_list_if_new 'smartdns' "$cfg" 'conf_files' "$outputConfig"
			;;
			smartdns.ipset)
				{ echo "domain-set -name adblock-fast -file $outputFile"; \
				echo "domain-rules /domain-set:adblock-fast/ -ipset adb"; } > "$outputConfig"
				uci_add_list_if_new 'smartdns' "$cfg" 'conf_files' "$outputConfig"
			;;
			smartdns.nftset)
				local nftset="#4:inet#fw4#adb4"
				[ "$ipv6_enabled" -ne '0' ] && nftset="${nftset},#6:inet#fw4#adb6"
				{ echo "domain-set -name adblock-fast -file $outputFile"; \
				echo "domain-rules /domain-set:adblock-fast/ -nftset $nftset"; } > "$outputConfig"
				uci_add_list_if_new 'smartdns' "$cfg" 'conf_files' "$outputConfig"
			;;
		esac
	}
	
	local param output_text i
	case $1 in
		cleanup)
			rm -f "$dnsmasqAddnhostsFile" "$dnsmasqAddnhostsCache" "${compressed_cache_dir}/${dnsmasqAddnhostsGzip}"
			rm -f "$dnsmasqConfFile" "$dnsmasqConfCache" "${compressed_cache_dir}/${dnsmasqConfGzip}"
			rm -f "$dnsmasqIpsetFile" "$dnsmasqIpsetCache" "${compressed_cache_dir}/${dnsmasqIpsetGzip}"
			rm -f "$dnsmasqNftsetFile" "$dnsmasqNftsetCache" "${compressed_cache_dir}/${dnsmasqNftsetGzip}"
			rm -f "$dnsmasqServersFile" "$dnsmasqServersCache" "${compressed_cache_dir}/${dnsmasqServersGzip}"
			rm -f "$smartdnsDomainSetFile" "$smartdnsDomainSetCache" "${compressed_cache_dir}/${smartdnsDomainSetGzip}" "$smartdnsDomainSetConfig"
			rm -f "$smartdnsIpsetFile" "$smartdnsIpsetCache" "${compressed_cache_dir}/${smartdnsIpsetGzip}" "$smartdnsIpsetConfig"
			rm -f "$smartdnsNftsetFile" "$smartdnsNftsetCache" "${compressed_cache_dir}/${smartdnsNftsetGzip}" "$smartdnsNftsetConfig"
			rm -f "$unboundFile" "$unboundCache" "${compressed_cache_dir}/${unboundGzip}"
			if [ -s "/etc/config/dhcp" ]; then
				config_load 'dhcp'
				config_foreach _dnsmasq_instance_config 'dnsmasq' 'cleanup'
				[ -n "$(uci_changes 'dhcp')" ] && uci_commit 'dhcp'
			fi
			if [ -s "/etc/config/smartdns" ]; then
				config_load 'smartdns'
				config_foreach _smartdns_instance_config 'smartdns' 'cleanup'
				[ -n "$(uci_changes 'smartdns')" ] && uci_commit 'smartdns'
			fi
		;;
		on_start)
			if [ ! -s "$outputFile" ]; then
				json set status 'statusFail'
				json add error 'errorOutputFileCreate'
				output "${_ERROR_}: $(get_text 'errorOutputFileCreate')!\n"
				return 1
			fi

			config_load 'dhcp'
			if [ "$dnsmasq_instance" = "*" ]; then
				config_foreach _dnsmasq_instance_config 'dnsmasq' "$dns"
			elif [ -n "$dnsmasq_instance" ]; then
				for i in $dnsmasq_instance; do
					_dnsmasq_instance_config "@dnsmasq[$i]" "$dns" || _dnsmasq_instance_config "$i" "$dns"
				done
			fi
			config_load 'smartdns'
			if [ "$smartdns_instance" = "*" ]; then
				config_foreach _smartdns_instance_config 'smartdns' "$dns"
			elif [ -n "$smartdns_instance" ]; then
				for i in $smartdns_instance; do
					_smartdns_instance_config "@smartdns[$i]" "$dns" || _smartdns_instance_config "$i" "$dns"
				done
			fi

			case "$dns" in
				dnsmasq.*)
					chmod 660 "$outputFile"
					chown root:dnsmasq "$outputFile" >/dev/null 2>/dev/null
					param='dnsmasq_restart'
					output_text='Restarting dnsmasq'
				;;
				smartdns.*)
					chmod 660 "$outputFile" "$outputConfig"
					chown root:root "$outputFile" "$outputConfig" >/dev/null 2>/dev/null
					param='smartdns_restart'
					output_text='Restarting SmartDNS'
				;;
				unbound.*)
					chmod 660 "$outputFile"
					chown root:unbound "$outputFile" >/dev/null 2>/dev/null
					param='unbound_restart'
					output_text='Restarting Unbound'
				;;
			esac

			if [ -n "$(uci_changes dhcp)" ]; then 
				uci_commit 'dhcp'
				if ! str_contains "$param" 'dnsmasq_restart'; then
					param="${param:+"$param; dnsmasq_restart"}"
					output_text="${output_text}/dnsmasq"
				fi
			fi
			if [ -n "$(uci_changes smartdns)" ]; then 
				uci_commit 'smartdns'
				if ! str_contains "$param" 'smartdns_restart'; then
					param="${param:+"$param; "}smartdns_restart"
					output_text="${output_text}/smartDNS"
				fi
			fi
			output 1 "$output_text "
			output 2 "$output_text "
			json set message "$output_text"
			if eval "$param"; then
				json set status 'statusSuccess'
				led_on "$led"
				output_okn
			else 
				output_fail
				json set status 'statusFail'
				json add error 'errorDNSReload'
				output "${_ERROR_}: $(get_text 'errorDNSReload')!\n"
				return 1
			fi
		;;
		on_stop)
			case "$dns" in
				dnsmasq.*)
					param='dnsmasq_restart'
				;;
				smartdns.*)
					param='smartdns_restart'
				;;
				unbound.*)
					param='unbound_restart'
				;;
			esac
			if [ -n "$(uci_changes dhcp)" ]; then 
				uci_commit 'dhcp'
				str_contains "$param" 'dnsmasq_restart' || param="${param:+"$param; dnsmasq_restart"}"
			fi
			if [ -n "$(uci_changes smartdns)" ]; then 
				uci_commit 'smartdns'
				str_contains "$param" 'smartdns_restart' || param="${param:+"$param; "}smartdns_restart"
			fi
			eval "$param"
			return $?
		;;
		quiet|quiet_restart)
			case "$dns" in
				dnsmasq.*)
					param='dnsmasq_restart'
				;;
				smartdns.*)
					param='smartdns_restart'
				;;
				unbound.*)
					param='unbound_restart'
				;;
			esac
			eval "$param"
			return $?
		;;
	esac
}

cache() {
	local R_TMP
	case "$1" in
		create|backup)
			[ -s "$outputFile" ] && { mv -f "$outputFile" "$outputCache"; } >/dev/null 2>/dev/null
			return $?
		;;
		restore|use)
			[ -s "$outputCache" ] && mv "$outputCache" "$outputFile" >/dev/null 2>/dev/null
			return $?
		;;
		test)
			[ -s "$outputCache" ]
			return $?
		;;
		test_gzip)
			[ -s "$outputGzip" ] && gzip -t -c "$outputGzip" >/dev/null 2>/dev/null
			return $?
		;;
		create_gzip)
			rm -f "$outputGzip" >/dev/null 2>/dev/null
			R_TMP="$(mktemp -u -q -t "${packageName}_tmp.XXXXXXXX")"
			if gzip < "$outputFile" > "$R_TMP"; then
				if mv "$R_TMP" "$outputGzip"; then
					rm -f "$R_TMP"
					return 0
				else
					rm -f "$R_TMP"
					return 1
				fi
			else
				return 1
			fi
		;;
		expand|unpack|unpack_gzip)
			[ -s "$outputGzip" ] && gzip -dc < "$outputGzip" > "$outputCache"
			return $?
		;;
	esac
}

process_file_url_wrapper() {
	if [ "$2" != '0' ]; then
		json add error 'errorConfigValidationFail'
		output "${_ERROR_}: $(get_text 'errorConfigValidationFail')!\n"
		output "Please check if the '$packageConfigFile' contains correct values for config options.\n"
	fi
	if [ "$parallel_downloads" -gt 0 ]; then
		process_file_url "$1" &
	else
		process_file_url "$1"
	fi
}

process_file_url() {
	local cfg="$1" new_size
	local label type D_TMP R_TMP filter
	if [ -z "$cfg" ] || [ -n "${2}${3}" ]; then
		url="$2"
		action="$3"
	fi

	[ "$enabled" = '1' ] || return 0
	[ -n "$url" ] || return 1

	label="${url##*//}"
	label="${label%%/*}"
	label="${name:-$label}"
	label="List: $label"
	case "$action" in
		allow) type='Allowed'; D_TMP="$A_TMP"
		;;
		block) type='Blocked'; D_TMP="$B_TMP"
		;;
		file) type='File'; D_TMP="$B_TMP"
		;;
	esac
	if is_https_url "$url" && [ -z "$isSSLSupported" ]; then
		output 1 "$_FAIL_"
		output 2 "[DL] $type $label $__FAIL__\n"
		echo "errorNoSSLSupport|${1}" >> "$runningErrorFile"
		return 0
	fi
	while [ -z "$R_TMP" ] || [ -e "$R_TMP" ]; do
		R_TMP="$(mktemp -u -q -t "${packageName}_tmp.XXXXXXXX")"
	done
	if [ -z "$url" ] || ! $dl_command "$url" "$dl_flag" "$R_TMP" 2>/dev/null || \
		[ ! -s "$R_TMP" ]; then
		output 1 "$_FAIL_"
		output 2 "[DL] $type $label $__FAIL__\n"
		echo "errorDownloadingList|${url}" >> "$runningErrorFile"
	else
		append_newline "$R_TMP"
		[ -n "$cfg" ] && new_size="$(get_local_filesize "$R_TMP")"
		if [ -n "$new_size" ] && [ "$size" != "$new_size" ]; then
			uci_set "$packageName" "$cfg" 'size' "$new_size"
		fi
		format="$(detect_file_type "$R_TMP")"
		case "$format" in
			adblockplus) filter="$adBlockPlusFilter";;
			dnsmasq) filter="$dnsmasqFileFilter";;
			dnsmasq2) filter="$dnsmasq2FileFilter";;
			dnsmasq3) filter="$dnsmasq3FileFilter";;
			domains) filter="$domainsFilter";;
			hosts) filter="$hostsFilter";;
			*)
				output 1 "$_FAIL_"
				output 2 "[DL] $type $label $__FAIL__\n"
				echo "errorDetectingFileType|${url}" >> "$runningErrorFile"
				rm -f "$R_TMP"
				return 0
			;;
		esac
		if [ -n "$filter" ] && [ "$action" != 'file' ]; then
			sed -i "$filter" "$R_TMP"
		fi
		if [ ! -s "$R_TMP" ]; then
			output 1 "$_FAIL_"
			output 2 "[DL] $type $label ($format) $__FAIL__\n"
			echo "errorParsingList|${url}" >> "$runningErrorFile"
		else
			append_newline "$R_TMP"
			cat "${R_TMP}" >> "$D_TMP"
			output 1 "$_OK_"
			output 2 "[DL] $type $label ($format) $__OK__\n"
		fi
	fi
	rm -f "$R_TMP"
	return 0
}

download_dnsmasq_file() {
	json set message "$(get_text 'statusDownloading')..."
	json set status 'statusDownloading'

	rm -f "$A_TMP" "$B_TMP" "$SED_TMP" "$outputFile" "$outputCache" "$outputGzip"
	if [ "$(get_ram_available)" -lt 32 ]; then
		output 3 'Low free memory, restarting resolver '
		if resolver 'quiet_restart'; then
			output_okn
		else 
			output_failn
		fi
	fi
	touch "$A_TMP" "$B_TMP" "$SED_TMP"
	output 1 'Downloading dnsmasq file '
	rm -f "$runningErrorFile"
	process_file_url '' "$dnsmasq_config_file_url" 'file'
	if [ -s "$runningErrorFile" ]; then
		while IFS= read -r line; do
			json add error "$line"
		done < "$runningErrorFile"
		rm -f "$runningErrorFile"
	fi
	output 2 'Moving dnsmasq file '
	if mv "$B_TMP" "$outputFile"; then
		output 2 "$__OK__\n"
	else
		output 2 "$__FAIL__\n"
		json add error 'errorMovingDataFile'
	fi
	output 1 '\n'
}

download_lists() {
# shellcheck disable=SC2317
	_ram_check() {
		_config_calculate_sizes() {
			local cfg="$1"
			local en size url
			config_get_bool en "$cfg" enabled '1'
			config_get size "$cfg" size
			config_get url "$cfg" url
			[ "$en" = '0' ] && return 0
			[ -n "$size" ] || size="$(get_url_filesize "$url")"
			[ -n "$size" ] && total_sizes=$((total_sizes+size))
		}
		local i free_mem total_sizes
		free_mem="$(get_ram_available)"
		if [ -z "$free_mem" ]; then
			json add warnning 'warningFreeRamCheckFail'
			output "${_WARNING_}: $(get_text 'warningFreeRamCheckFail')!\n"
			return 0
		fi
		config_load "$packageName"
		config_foreach _config_calculate_sizes 'file_url'
		if [ $((free_mem)) -lt $((total_sizes * 2)) ]; then
			json add error 'errorTooLittleRam' "$free_mem"
			output "${_ERROR_}: $(get_text 'errorTooLittleRam' "$free_mem")!\n"
			return 1
		else
			return 0
		fi
	}
	local hf j=0 R_TMP

	_ram_check || return 1

	json set message "$(get_text 'statusDownloading')..."
	json set status 'statusDownloading'

	rm -f "$A_TMP" "$B_TMP" "$SED_TMP" "$outputFile" "$outputCache" "$outputGzip"
	if [ "$(get_ram_total)" -lt 33554432 ]; then
		output 3 'Low free memory, restarting resolver '
		if resolver 'quiet_restart'; then
			output_okn
		else 
			output_failn
		fi
	fi
	touch "$A_TMP" "$B_TMP" "$SED_TMP"
	output 1 'Downloading lists '
	rm -f "$runningErrorFile"
	config_load "$packageName"
	config_foreach load_validate_file_url_section 'file_url' process_file_url_wrapper
	wait
	if [ -n "$(uci_changes "$packageName")" ]; then 
		output 2 "Saving updated file size(s) "
		if uci_commit "$packageName"; then output_ok; else output_fail; fi
	fi
	output 1 '\n'

	if [ -s "$runningErrorFile" ]; then
		while IFS= read -r line; do
			json add error "$line"
		done < "$runningErrorFile"
		rm -f "$runningErrorFile"
	fi

	if [ "$canary_domains_icloud" -ne '0' ]; then
		canaryDomains="${canaryDomains:+$canaryDomains }${canaryDomainsiCloud}"
	fi
	if [ "$canary_domains_mozilla" -ne '0' ]; then
		canaryDomains="${canaryDomains:+$canaryDomains }${canaryDomainsMozilla}"
	fi

	append_newline "$B_TMP"
	for hf in $blocked_domain $canaryDomains; do
		printf "%s\n" "$(echo "$hf" | sed "$domainsFilter")" >> "$B_TMP"
	done
	sed -i '/^[[:space:]]*$/d' "$B_TMP"
	[ ! -s "$B_TMP" ] && return 1

	allowed_domain="${allowed_domain}
$(sed '/^[[:space:]]*$/d' "$A_TMP")"

	output 1 'Processing downloads '
	output 2 'Sorting combined list '
	json set status 'statusProcessing'
	json set message "$(get_text 'statusProcessing'): sorting combined list"
	if [ "$allow_non_ascii" -gt 0 ]; then
		if sort -u "$B_TMP" > "$A_TMP"; then
			output_ok
		else
			output_fail
			json add error 'errorSorting'
		fi
	else
		if sort -u "$B_TMP" | grep -E -v '[^a-zA-Z0-9=/.-]' > "$A_TMP"; then
			output_ok
		else
			output_fail
			json add error 'errorSorting'
		fi
	fi

	case "$dns" in
		'dnsmasq.conf' | 'dnsmasq.ipset' | 'dnsmasq.nftset' | 'dnsmasq.servers' | \
		'smartdns.domainset' | 'smartdns.ipset' | 'smartdns.nftset' | \
		'unbound.adb_list' )
			# TLD optimization written by Dirk Brenken (dev@brenken.org)
			output 2 'Optimizing combined list '
			json set message "$(get_text 'statusProcessing'): optimizing combined list"
	# 	sed -E 'G;:t;s/(.*)(\.)(.*)(\n)(.*)/\1\4\5\2\3/;tt;s/(.*)\n(\.)(.*)/\3\2\1/' is actually slower than command below
	# shellcheck disable=SC2016
			if $awk -F "." '{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' "$A_TMP" > "$B_TMP"; then
				if sort "$B_TMP" > "$A_TMP"; then
					if $awk '{if(NR=1){tld=$NF};while(getline){if($NF!~tld"\\."){print tld;tld=$NF}}print tld}' "$A_TMP" > "$B_TMP"; then
						if $awk -F "." '{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' "$B_TMP" > "$A_TMP"; then
							if sort -u "$A_TMP" > "$B_TMP"; then
								output_ok
							else
								output_failn
								json add error 'errorOptimization'
								mv "$A_TMP" "$B_TMP"
							fi
						else
							output_failn
							json add error 'errorOptimization'
						fi
					else
						output_failn
						json add error 'errorOptimization'
						mv "$A_TMP" "$B_TMP"
					fi
				else
					output_failn
					json add error 'errorOptimization'
				fi
			else
				output_failn
				json add error 'errorOptimization'
				mv "$A_TMP" "$B_TMP"
			fi
		;;
		*)
			mv "$A_TMP" "$B_TMP"
		;;
	esac

	if [ -n "$allowed_domain" ]; then
		output 2 'Removing allowed domains from combined list'
		json set message "$(get_text 'statusProcessing'): allowing domains"
		for hf in ${allowed_domain}; do
			hf="$(echo "$hf" | sed 's/\./\\./g')"
			echo "/(^|\.)${hf}$/d;" >> "$SED_TMP"
		done
		if [ -s "$SED_TMP" ]; then
			if sed -i -E -f "$SED_TMP" "$B_TMP"; then
				output_ok
			else
				output_failn
				json add error 'errorAllowListProcessing'
			fi
		else
			output_failn
			json add error 'errorAllowListProcessing'
		fi
	fi

	output 2 'Formatting combined list file '
	json set message "$(get_text 'statusProcessing'): formatting combined list file"
	if [ -z "$outputFilterIPv6" ]; then
		if sed "$outputFilter" "$B_TMP" > "$A_TMP"; then
			output_ok
		else
			output_failn
			json add error 'errorDataFileFormatting'
		fi
	else
		case "$dns" in
			dnsmasq.addnhosts)
				if sed "$outputFilter" "$B_TMP" > "$A_TMP" && \
					sed "$outputFilterIPv6" "$B_TMP" >> "$A_TMP"; then
					output_ok
				else
					output_failn
					json add error 'errorDataFileFormatting'
				fi
			;;
		esac
	fi

	if [ -n "$outputAllowFilter" ] && [ -n "$allowed_domain" ]; then
		rm -f "$SED_TMP"; touch "$SED_TMP";
		output 2 'Allowing domains '
		json set message "$(get_text 'statusProcessing'): allowing domains"
		for hf in ${allowed_domain}; do
			echo "$hf" | sed -E "$outputAllowFilter" >> "$SED_TMP"
		done
		if [ -s "$SED_TMP" ]; then
			if cat "$SED_TMP" "$A_TMP" > "$B_TMP"; then
				output_ok
			else
				output_failn
				json add error 'errorAllowListProcessing'
			fi
		else
			output_failn
			json add error 'errorAllowListProcessing'
		fi
	else
		mv "$A_TMP" "$B_TMP"
	fi

	case "$dns" in
		dnsmasq.addnhosts)
			output 2 'Creating dnsmasq addnhosts file '
			json set message "$(get_text 'statusProcessing'): creating dnsmasq addnhosts file"
		;;
		dnsmasq.conf)
			output 2 'Creating dnsmasq config file '
			json set message "$(get_text 'statusProcessing'): creating dnsmasq config file"
		;;
		dnsmasq.ipset)
			output 2 'Creating dnsmasq ipset file '
			json set message "$(get_text 'statusProcessing'): creating dnsmasq ipset file"
		;;
		dnsmasq.nftset)
			output 2 'Creating dnsmasq nft set file '
			json set message "$(get_text 'statusProcessing'): creating dnsmasq nft set file"
		;;
		dnsmasq.servers)
			output 2 'Creating dnsmasq servers file '
			json set message "$(get_text 'statusProcessing'): creating dnsmasq servers file"
		;;
		smartdns.domainset)
			output 2 'Creating smartdns domain-set file '
			json set message "$(get_text 'statusProcessing'): creating smartdns domain-set file"
		;;
		smartdns.ipset)
			output 2 'Creating smartdns domain-set file '
			json set message "$(get_text 'statusProcessing'): creating smartdns ipset file"
		;;
		smartdns.nftset)
			output 2 'Creating smartdns domain-set file '
			json set message "$(get_text 'statusProcessing'): creating smartdns nft set file"
		;;
		unbound.adb_list)
			output 2 'Creating Unbound adb_list file '
			json set message "$(get_text 'statusProcessing'): creating Unbound adb_list file"
		;;
	esac

	if mv "$B_TMP" "$outputFile"; then
		output_ok
	else
		output_failn
		json add error 'errorMovingDataFile'
	fi
	case "$dns" in
		unbound.adb_list)
			sed -i '1 i\server:' "$outputFile"
		;;
	esac
	if [ "$compressed_cache" -gt 0 ]; then
		output 2 'Creating compressed cache '
		json set message "$(get_text 'statusProcessing'): creating compressed cache"
		if cache 'create_gzip'; then
			output_ok
		else
			output_failn
			json add error 'errorCreatingCompressedCache'
		fi
	else
		rm -f "$outputGzip"
	fi
	output 2 'Removing temporary files '
	json set message "$(get_text 'statusProcessing'): removing temporary files"
	rm -f "/tmp/${packageName}_tmp.*" "$A_TMP" "$B_TMP" "$SED_TMP" "$outputCache" || j=1
	if [ $j -eq 0 ]; then
		output_ok
	else
		output_failn
		json add error 'errorRemovingTempFiles'
	fi
	output 1 '\n'
}

adb_allow() {
	local c hf string="$1"
	local validation_result="$3"
	load_environment "$validation_result" 'quiet' || return 1
	if [ ! -s "$outputFile" ]; then
		output "No block-list ('$outputFile') found.\n"
		return 0
	elif [ -z "$string" ]; then
		output "Usage: /etc/init.d/${packageName} allow 'domain' ...\n"
		return 0
	elif [ -n "$dnsmasq_config_file_url" ]; then
		output "Allowing individual domains is not possible when using external dnsmasq config file.\n"
		return 0
	fi
	case "$dns" in
		dnsmasq.*)
			output 1 "Allowing domain(s) and restarting dnsmasq "
			output 2 "Allowing domain(s) \n"
			for c in $string; do
				output 2 "  $c "
				hf="$(echo "$c" | sed 's/\./\\./g')"
				if sed -i "\:\(/\|\.\)${hf}/:d" "$outputFile" && \
					uci_add_list_if_new "${packageName}" 'config' 'allowed_domain' "$c"; then
						output_ok
				else
					output_fail
				fi
				if [ -n "$outputAllowFilter" ]; then
					if echo "$c" | sed -E "$outputAllowFilter" >> "$outputFile" && \
						uci_add_list_if_new "${packageName}" 'config' 'allowed_domain' "$c"; then
							output_ok
					else
						output_fail
					fi
				fi
			done
			if [ "$compressed_cache" -gt 0 ]; then
				output 2 'Creating compressed cache '
				if cache 'create_gzip'; then
					output_ok
				else
					output_fail
				fi
			fi
			output 2 "Committing changes to config "
			if uci_commit "$packageName"; then
				allowed_domain="$(uci_get "$packageName" 'config' 'allowed_domain')"
				config_cache 'create'
				json set stats "$serviceName is blocking $(count_blocked_domains) domains (with ${dns})"
				output_ok
				if [ "$dns" = 'dnsmasq.ipset' ]; then
					output 2 "Flushing adb ipset "
					if ipset -q -! flush adb; then output_ok; else output_fail; fi
				fi
				if [ "$dns" = 'dnsmasq.nftset' ]; then
					output 2 "Flushing adb nft sets "
					nft flush set inet fw4 adb6
					if nft flush set inet fw4 adb4; then output_ok; else output_fail; fi
				fi
				output 2 "Restarting dnsmasq "
				if dnsmasq_restart; then output_okn; else output_failn; fi
			else 
				output_failn
			fi
		;;
		smartdns.*)
			output 1 "Allowing domain(s) and restarting smartdns "
			output 2 "Allowing domain(s) \n"
			for c in $string; do 
				output 2 "  $c "
				hf="$(echo "$c" | sed 's/\./\\./g')"
				if sed -i "\:\(\"\|\.\)${hf}\":d" "$outputFile" && \
					uci_add_list_if_new "$packageName" 'config' 'allowed_domain' "$string"; then
						output_ok
				else
					output_fail
				fi
			done
			if [ "$compressed_cache" -gt 0 ]; then
				output 2 'Creating compressed cache '
				if cache 'create_gzip'; then
					output_ok
				else
					output_fail
				fi
			fi
			output 2 "Committing changes to config "
			if uci_commit "$packageName"; then
				allowed_domain="$(uci_get "$packageName" 'config' 'allowed_domain')"
				config_cache 'create'
				json set stats "$serviceName is blocking $(count_blocked_domains) domains (with ${dns})"
				output_ok; 
				output 2 "Restarting Unbound "
				if unbound_restart; then output_okn; else output_failn; fi
			else 
				output_failn
			fi
		;;
		unbound.*)
			output 1 "Allowing domain(s) and restarting Unbound "
			output 2 "Allowing domain(s) \n"
			for c in $string; do 
				output 2 "  $c "
				hf="$(echo "$c" | sed 's/\./\\./g')"
				if sed -i "\:\(\"\|\.\)${hf}\":d" "$outputFile" && \
					uci_add_list_if_new "$packageName" 'config' 'allowed_domain' "$string"; then
						output_ok
				else
					output_fail
				fi
			done
			if [ "$compressed_cache" -gt 0 ]; then
				output 2 'Creating compressed cache '
				if cache 'create_gzip'; then
					output_ok
				else
					output_failn
				fi
			fi
			output 2 "Committing changes to config "
			if uci_commit "$packageName"; then
				allowed_domain="$(uci_get "$packageName" 'config' 'allowed_domain')"
				config_cache 'create'
				json set stats "$serviceName is blocking $(count_blocked_domains) domains (with ${dns})"
				output_ok; 
				output 2 "Restarting Unbound "
				if unbound_restart; then output_okn; else output_failn; fi
			else 
				output_failn
			fi
		;;
	esac
}

adb_check() {
	local c param="$1"
	local validation_result="$3"
	load_environment "$validation_result" 'quiet' || return 1
	if [ ! -s "$outputFile" ]; then
		output "No block-list ('$outputFile') found.\n"
		return 0
	elif [ -z "$param" ]; then
		output "Usage: /etc/init.d/${packageName} check 'domain' ...\n"
		return 0
	fi
	for string in ${param}; do
		c="$(grep -c "$string" "$outputFile")"
		if [ "$c" -gt 0 ]; then
			if [ "$c" -eq 1 ]; then
				output "Found 1 match for '$string' in '$outputFile'.\n"
			else
				output "Found $c matches for '$string' in '$outputFile'.\n"
			fi
			if [ "$c" -le 20 ]; then
				grep "$string" "$outputFile" | sed "$outputOutputFilter"
			fi
		else
			output "The '$string' is not found in current block-list ('$outputFile').\n"
		fi
	done
}

adb_check_lists() {
# shellcheck disable=SC2317
	_check_list() {
		local cfg="$1"
		local en size url R_TMP string c
		config_get_bool en "$cfg" enabled '1'
		config_get action "$cfg" action 'block'
		config_get url "$cfg" url
		[ "$en" = '0' ] && return 0
		[ "$action" != 'block' ] && return 0
		if is_https_url "$url" && [ -z "$isSSLSupported" ]; then
			output "[DL] $url $__FAIL__\n"
		fi
		while [ -z "$R_TMP" ] || [ -e "$R_TMP" ]; do
			R_TMP="$(mktemp -u -q -t "${packageName}_tmp.XXXXXXXX")"
		done
		if [ -z "$url" ] || ! $dl_command "$url" "$dl_flag" "$R_TMP" 2>/dev/null || \
			[ ! -s "$R_TMP" ]; then
			output "[DL] $url $__FAIL__\n"
		else
			append_newline "$R_TMP"
			for string in ${param}; do
				c="$(grep -c "$string" "$R_TMP")"
				if [ "$c" -gt 0 ]; then
					if [ "$c" -eq 1 ]; then
						output "Found 1 match for '$string' in '$url'.\n"
					else
						output "Found $c matches for '$string' in '$url'.\n"
					fi
					grep "$string" "$R_TMP"
				else
					output "The '$string' is not found in '$url'.\n"
				fi
			done
		rm -f "$R_TMP"
		fi
	}
	local param="$1"
	local validation_result="$3"
	load_environment "$validation_result" 'quiet' || return 1
	if [ -z "$param" ]; then
		output "Usage: /etc/init.d/${packageName} check_lists 'domain' ...\n"
		return 0
	fi
	config_load "$packageName"
	config_foreach _check_list 'file_url'
	return 0
}

adb_config_update() {
# shellcheck disable=SC2317
	_cleanup_missing_urls() {
		local cfg="$1" url size
		config_get url "$cfg" url
		if [ -z "$url" ]; then
			uci_delete "$packageName" "$cfg"
		fi
	}
	local R_TMP label
	local param validation_result="$3"
	case "$1" in
		on_boot) param="$1";;
		*) param='quiet';;
	esac
	load_environment "$validation_result" "$param" || return 1
	label="${config_update_url##*//}"
	label="${label%%/*}";
	[ "$config_update_enabled" -ne '0' ] || return 0

	if [ "$param" != 'download' ]; then
		cache 'test' && return 0 
		cache 'test_gzip' && return 0 
	fi
	output 1 'Updating config '
	while [ -z "$R_TMP" ] || [ -e "$R_TMP" ]; do
		R_TMP="$(mktemp -u -q -t "${packageName}_tmp.XXXXXXXX")"
	done
	if ! $dl_command "$config_update_url" "$dl_flag" "$R_TMP" 2>/dev/null || [ ! -s "$R_TMP" ]; then
		append_newline "$R_TMP"
		output 1 "$_FAIL_\n"
		output 2 "[DL] Config  Update:  $label $__FAIL__\n"
		json add error 'errorDownloadingConfigUpdate'
	else
		if [ -s "$R_TMP" ] && sed -f "$R_TMP" -i "$packageConfigFile" 2>/dev/null; then
			output 1 "$_OK_\n"
			output 2 "[DL] Config  Update:  $label $__OK__\n"
		else
			output 1 "$_FAIL_\n"
			output 2 "[DL] Config  Update:  $label $__FAIL__\n"
			json add error 'errorParsingConfigUpdate'
		fi
	fi
	rm -f "$R_TMP"
	config_load "$packageName"
	config_foreach _cleanup_missing_urls 'file_url'
	[ -n "$(uci_changes "$packageName")" ] && uci_commit "$packageName"
	return 0
}

adb_show_blocklist() {
	local validation_result="$3"
	load_environment "$validation_result" 'quiet' || return 1
	sed "$outputOutputFilter" "$outputFile"
}

adb_sizes() {
# shellcheck disable=SC2317
	_config_add_url_size() {
		local cfg="$1" url name size
		config_get url "$cfg" url
		config_get name "$cfg" name
		size="$(get_url_filesize "$url")"
		output "${name:-$url}${size:+: $size} "
		if [ -n "$size" ]; then
			uci_set "$packageName" "$cfg" 'size' "$size"
			output_okn
		else
			output_failn
		fi
	}
	local i
	local validation_result="$3"
	load_environment "$validation_result" 'quiet' || return 1
	config_load "$packageName"
	config_foreach _config_add_url_size 'file_url'
	[ -n "$(uci_changes "$packageName")" ] && uci_commit "$packageName"
}

# shellcheck disable=SC2120
adb_start() {
	local action status error message stats c iface
	local param="$1" validation_result="$3"

	load_environment "$validation_result" "$param" || return 1

	status="$(json get 'status')"
	error="$(json get 'error')"
	message="$(json get 'message')"
	stats="$(json get 'stats')"
	action="$(config_cache get 'trigger_service')"
	fw4_restart_flag="$(config_cache get 'trigger_fw4')"

	if [ "$action" = 'on_boot' ] || [ "$param" = 'on_boot' ] || [ "$param" = 'on_pause' ]; then
		if cache 'test_gzip' || cache 'test'; then
			action='restore'
		else
			action='download'
		fi
	elif [ "$action" = 'download' ] || [ "$param" = 'download' ] || [ -n "$error" ]; then
		action='download'
	elif [ ! -s "$outputFile" ]; then 
		if cache 'test_gzip' || cache 'test'; then
			action='restore'
		else
			action='download'
		fi
	elif [ "$action" = 'restart' ] || [ "$param" = 'restart' ]; then
		action='restart'
	elif [ -s "$outputFile" ] && [ "$status" = "statusSuccess" ] && [ -z "$error" ]; then
		status_service 'quiet'
		return 0
	else
		action='download'
	fi

	json del all
	config_cache 'create'

	if [ "$action" = 'restore' ]; then
		output 0 "Starting $serviceName... "
		output 3 "Starting $serviceName...\n"
		json set status 'statusStarting'
		if cache 'test_gzip' && ! cache 'test' && [ ! -s "$outputFile" ]; then
			output 3 'Found compressed cache file, unpacking it '
			json set message 'found compressed cache file, unpacking it.'
			if cache 'unpack_gzip'; then
				output_okn
			else
				output_failn
				json add error 'errorRestoreCompressedCache'
				output "${_ERROR_}: $(get_text 'errorRestoreCompressedCache')!\n"
				action='download'
			fi
		fi
		if cache 'test' && [ ! -s "$outputFile" ]; then
			output 3 'Found cache file, reusing it '
			json set message 'found cache file, reusing it.'
			if cache 'restore'; then 
				output_okn
				resolver 'on_start'
			else
				output_failn
				json add error 'errorRestoreCache'
				output "${_ERROR_}: $(get_text 'errorRestoreCache')!\n"
				action='download'
			fi
		fi
	fi
	if [ "$action" = 'download' ]; then
		if [ -z "$blocked_url" ] && [ -z "$blocked_domain" ]; then
			json set status 'statusFail'
			json add error 'errorNothingToDo'
			output "${_ERROR_}: $(get_text 'errorNothingToDo')!\n"
		else
			if [ -s "$outputFile" ] || cache 'test' || cache 'test_gzip'; then
				output 0 "Force-reloading $serviceName... "
				output 3 "Force-reloading $serviceName...\n"
				json set status 'statusForceReloading'
			else
				output 0 "Starting $serviceName... "
				output 3 "Starting $serviceName...\n"
				json set status 'statusStarting'
			fi
			resolver 'cleanup'
			if [ "$dns" = 'dnsmasq.conf' ] && [ -n "$dnsmasq_config_file_url" ]; then
				download_dnsmasq_file
			else
				download_lists
			fi
			resolver 'on_start'
		fi
	fi
	if [ "$action" = 'restart' ]; then
		output 0 "Restarting $serviceName... "
		output 3 "Restarting $serviceName...\n"
		json set status 'statusRestarting'
		resolver 'on_start'
	fi
	if [ "$action" = 'start' ]; then
		output 0 "Starting $serviceName... "
		output 3 "Starting $serviceName...\n"
		json set status 'statusStarting'
		resolver 'on_start'
	fi
	if [ -s "$outputFile" ] && [ "$(json get status)" != "statusFail" ]; then
		output 0 "$__OK__\n";
		json del message
		json set status 'statusSuccess'
		json set stats "$serviceName is blocking $(count_blocked_domains) domains (with ${dns})"
		status_service 'quiet'

	else
		output 0 "$__FAIL__\n";
		json set status 'statusFail'
		json add error 'errorOhSnap'
		status_service 'quiet'
	fi

	procd_open_instance 'main'
	procd_set_param command /bin/true
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_open_data
	json_add_string 'status' "$(json get status)"
	json_add_string 'errors' "$(json get error)"
	json_add_string 'warnings' "$(json get warning)"
	if [ -s "$outputFile" ]; then
		json_add_int 'entries' "$(count_blocked_domains)"
	else
		json_add_int 'entries' '0'
	fi
	json_add_array firewall
	if [ "$force_dns" -ne '0' ]; then
# shellcheck disable=SC3060
		for c in ${force_dns_port/,/ }; do
			if netstat -tuln | grep LISTEN | grep ":${c}" >/dev/null 2>&1; then
				for iface in $force_dns_interface; do
					json_add_object ""
					json_add_string type redirect
					json_add_string target DNAT
					json_add_string src "$iface"
					json_add_string proto "tcp udp"
					json_add_string src_dport "$c"
					json_add_string dest_port "$c"
					json_add_string family any
					json_add_boolean reflection 0
					json_close_object
				done
			else
				for iface in $force_dns_interface; do
					json_add_object ""
					json_add_string type rule
					json_add_string src "$iface"
					json_add_string dest "*"
					json_add_string proto "tcp udp"
					json_add_string dest_port "$c"
					json_add_string target REJECT
					json_close_object
				done
			fi
		done
	fi
	case "$dns" in
		dnsmasq.ipset|smartdns.ipset)
			json_add_object ""
			json_add_string type ipset
			json_add_string name adb
			json_add_string match dest_net
			json_add_string storage hash
			json_close_object
			for iface in $force_dns_interface; do
				json_add_object ""
				json_add_string type rule
				json_add_string ipset adb
				json_add_string src "$iface"
				json_add_string dest "*"
				json_add_string proto "tcp udp"
				json_add_string target REJECT
				json_close_object
			done
		;;
		dnsmasq.nftset|smartdns.nftset)
			json_add_object ""
			json_add_string type ipset
			json_add_string name adb4
			json_add_string family 4
			json_add_string match dest_net
			json_close_object
			for iface in $force_dns_interface; do
				json_add_object ""
				json_add_string type rule
				json_add_string ipset adb4
				json_add_string src "$iface"
				json_add_string dest "*"
				json_add_string proto "tcp udp"
				json_add_string target REJECT
				json_close_object
			done
			if [ "$ipv6_enabled" -ne '0' ]; then
				json_add_object ""
				json_add_string type ipset
				json_add_string name adb6
				json_add_string family 6
				json_add_string match dest_net
				json_close_object
				for iface in $force_dns_interface; do
					json_add_object ""
					json_add_string type rule
					json_add_string ipset adb6
					json_add_string src "$iface"
					json_add_string dest "*"
					json_add_string proto "tcp udp"
					json_add_string target REJECT
					json_close_object
				done
			fi
		;;
	esac
	json_close_array
	procd_close_data
	procd_close_instance
	return 0
}

adb_status() {
	local param="$1"
	local c status message error warning stats text
	status="$(json get status)"
	message="$(json get message)"
	error="$(json get error)"
	warning="$(json get warning)"
	stats="$(json get stats)"
	if [ "$status" = "statusSuccess" ]; then
		output "$stats "; output_okn;
	else
		[ -n "$status" ] && status="$(get_text "$status")"
		if [ -n "$status" ] && [ -n "$message" ]; then 
			status="${status}: $message"
		fi
		[ -n "$status" ] && output "$serviceName $status!\n"
	fi
	if [ "$param" != 'quiet' ] && [ -n "$error" ]; then
		for c in $error; do
			local error_param="${c##*|}"
			local error_code="${c%|*}"
			output "${_ERROR_}: $(get_text "$error_code" "$error_param")!\n"
		done
	fi
	if [ "$param" != 'quiet' ] && [ -n "$warning" ]; then
		for c in $warning; do
			local warning_param="${c##*|}"
			local warning_code="${c%|*}"
			output "${_WARNING_}: $(get_text "$warning_code" "$warning_param").\n"
		done
	fi
	return 0
}

# shellcheck disable=SC2120
adb_stop() {
	local validation_result="$3"
	load_environment "$validation_result" 'quiet' || return 0
	if [ -s "$outputFile" ]; then
		output "Stopping $serviceName... "
		cache 'create'
		if resolver 'on_stop'; then
			ipset -q -! flush adb
			ipset -q -! destroy adb
			nft delete set inet fw4 adb4
			nft delete set inet fw4 adb6
			led_off "$led"
			output 0 "$__OK__\n"; output_okn;
			json set status 'statusStopped'
			json del message
		else 
			output 0 "$__FAIL__\n"; output_fail;
			json set status 'statusFail'
			json add error 'errorStopping'
			output "${_ERROR_}: $(get_text 'errorStopping')!\n"
		fi
	fi
	return 0
}

adb_pause() {
	local timeout="${1:-$pause_timeout}"
	local validation_result="$3"
	adb_stop 'on_pause' '' "$validation_result"
	output "Sleeping for $timeout seconds... "
	if is_integer "$timeout" && sleep "$timeout"; then
		output_okn
	else
		output_failn
	fi
	adb_start 'on_pause' '' "$validation_result"
}

allow() { load_validate_config 'config' adb_allow "'$*'"; }
boot() {
	local procd_boot_delay
	ubus -t 30 wait_for network.interface 2>/dev/null
	config_load "$packageName"
	config_get procd_boot_delay 'config' 'procd_boot_delay' '0'
# shellcheck disable=SC2154
	{ is_integer "$procd_boot_delay" && sleep "$procd_boot_delay"; \
		rc_procd start_service 'on_boot' && service_started 'on_boot'; } &
}
check() { load_validate_config 'config' adb_check "'$*'"; }
check_lists() { load_validate_config 'config' adb_check_lists "'$*'"; }
dl() { rc_procd start_service 'download'; }
killcache() {
	local compressed_cache_dir
	config_load "$packageName"
	config_get compressed_cache_dir 'config' 'compressed_cache_dir' '/etc'
	if [ "$(sanitize_dir "$compressed_cache_dir")" = '/' ]; then
		compressed_cache_dir=''
	elif [ -n "$(sanitize_dir "$compressed_cache_dir")" ]; then
		compressed_cache_dir="$(sanitize_dir "$compressed_cache_dir")"
	else
		compressed_cache_dir="/etc"
	fi
	rm -f "$dnsmasqAddnhostsCache" "${compressed_cache_dir}/${dnsmasqAddnhostsGzip}"
	rm -f "$dnsmasqConfCache" "${compressed_cache_dir}/${dnsmasqConfGzip}"
	rm -f "$dnsmasqIpsetCache" "${compressed_cache_dir}/${dnsmasqIpsetGzip}"
	rm -f "$dnsmasqNftsetCache" "${compressed_cache_dir}/${dnsmasqNftsetGzip}"
	rm -f "$dnsmasqServersCache" "${compressed_cache_dir}/${dnsmasqServersGzip}"
	rm -f "$smartdnsDomainSetCache" "${compressed_cache_dir}/${smartdnsDomainSetGzip}"
	rm -f "$smartdnsIpsetCache" "${compressed_cache_dir}/${smartdnsIpsetGzip}"
	rm -f "$smartdnsNftsetCache" "${compressed_cache_dir}/${smartdnsNftsetGzip}"
	rm -f "$unboundCache" "${compressed_cache_dir}/${unboundGzip}"
	resolver 'cleanup'
	return 0
}
show_blocklist() { load_validate_config 'config' adb_show_blocklist "'$*'"; }
reload_service() { rc_procd start_service 'restart'; }
restart_service() { rc_procd start_service 'restart'; }
service_started() { is_fw4_restart_needed && procd_set_config_changed firewall; }
service_stopped() { is_fw4_restart_needed && procd_set_config_changed firewall; }
service_triggers() {
	local wan wan6 i
	local procd_trigger_wan6
	config_load "$packageName"
	config_get_bool procd_trigger_wan6 'config' 'procd_trigger_wan6' '0'
	network_flush_cache
	network_find_wan wan
	wan="${wan:-wan}"
	if [ "$procd_trigger_wan6" -ne '0' ]; then
		network_find_wan6 wan6
		wan6="${wan6:-wan6}"
	fi
	for i in "$wan" "$wan6"; do
		[ -n "$i" ] && procd_add_interface_trigger "interface.*" "$i" "/etc/init.d/${packageName}" start
	done
	procd_add_config_trigger "config.change" "$packageName" "/etc/init.d/${packageName}" reload
}
sizes() { load_validate_config 'config' adb_sizes "''"; }
start_service() { 
	load_validate_config 'config' adb_config_update "'$*'"
	load_validate_config 'config' adb_start "'$*'"
}
status_service() { adb_status "$@"; }
stop_service() { load_validate_config 'config' adb_stop "'$*'"; }
pause() { load_validate_config 'config' adb_pause "'$*'"; }
version() { echo "$PKG_VERSION"; }

load_validate_file_url_section() {
	uci_load_validate "$packageName" "$packageName" "$1" "$2" \
		'enabled:bool:1' \
		'action:or("allow", "block"):block' \
		'size:or(uinteger, "")' \
		'name:string' \
		'url:string'
}

load_validate_config() {
	local enabled
	local force_dns
	local force_dns_interface
	local force_dns_port
	local parallel_downloads
	local debug
	local compressed_cache
	local compressed_cache_dir
	local ipv6_enabled
	local allow_non_ascii
	local canary_domains_icloud
	local canary_domains_mozilla
	local config_update_enabled
	local config_update_url
	local download_timeout
	local pause_timeout
	local curl_additional_param
	local curl_max_file_size
	local curl_retry
	local verbosity
	local procd_trigger_wan6
	local procd_boot_wan_timeout
	local procd_lan_interface_name
	local led
	local dns
	local dnsmasq_instance
	local allowed_domain
	local blocked_domain
	local dnsmasq_config_file_url
	uci_load_validate "$packageName" "$packageName" "$1" "${2}${3:+ $3}" \
		'enabled:bool:0' \
		'force_dns:bool:1' \
		'force_dns_interface:list(network):lan' \
		'force_dns_port:list(integer):53,853' \
		'parallel_downloads:bool:1' \
		'debug:bool:0' \
		'compressed_cache:bool:0' \
		'compressed_cache_dir:directory:/etc' \
		'ipv6_enabled:bool:0' \
		'allow_non_ascii:bool:0' \
		'canary_domains_icloud:bool:0' \
		'canary_domains_mozilla:bool:0' \
		'config_update_enabled:bool:0' \
		'config_update_url:string:https://cdn.jsdelivr.net/gh/openwrt/packages/net/adblock-fast/files/adblock-fast.config.update' \
		'download_timeout:range(1,60):20' \
		'pause_timeout:range(1,60):20' \
		'curl_additional_param:or("", string)' \
		'curl_max_file_size:or("", uinteger)' \
		'curl_retry:range(0,30):3' \
		'verbosity:range(0,2):2' \
		'procd_trigger_wan6:bool:0' \
		'procd_boot_wan_timeout:integer:60' \
		'led:or("", "none", file, device, string)' \
		'dns:or("dnsmasq.addnhosts", "dnsmasq.conf", "dnsmasq.ipset", "dnsmasq.nftset", "dnsmasq.servers", "smartdns.domainset", "smartdns.ipset", "smartdns.nftset", "unbound.adb_list"):dnsmasq.servers' \
		'dnsmasq_instance:list(or(integer, string)):*' \
		'smartdns_instance:list(or(integer, string)):*' \
		'allowed_domain:list(string)' \
		'blocked_domain:list(string)' \
		'dnsmasq_config_file_url:string'
}
